<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/8/14
 * Time: 下午11:31
 */
namespace PddWechat\Models\User\Service;

use Dai\Framework\Base\BaseSessionInfo;
use Dai\Framework\Library\CacheClass;
use PddWechat\Models\User\Data\UserData;
use PddWechat\Models\User\Dto\WeChatUserTeamCount;

class TeamCount
{
    public function __construct()
    {
        $this->userData = new UserData();
    }

    public function execute($basePageInfo)
    {
        /** @var BaseSessionInfo $sessionData */
        $sessionData = $basePageInfo->sessionInfo;
        $uid = $sessionData->uid;
        $tag = "UserUid_" . $uid;
        $userCount = CacheClass::cacheDataByRedis(__METHOD__, $tag, function () use ($uid) {
            return $this->countTeamUsersNum($uid);
        },60);
        return $userCount;
    }

    private function countTeamUsersNum($uid) {

        $beginToday = date("Y-m-d H:i:s", mktime(0,0,0,date('m'),date('d'),date('Y')));
        $endToday = date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1);
        $todayDirNum = $this->userData->getDirectMemberNumByUidAndCreateTime($uid,$beginToday,$endToday);

        $beginWeek = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
        $endWeek = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
        $weekDirNum = $this->userData->getDirectMemberNumByUidAndCreateTime($uid,$beginWeek,$endWeek);

        $beginMonth = date("Y-m-d H:i:s", mktime(0,0,0,date('m'),1,date('Y')));
        $endMonth = date("Y-m-d H:i:s", mktime(23,59,59,date('m'),date('t'),date('Y')));
        $monthDirNum = $this->userData->getDirectMemberNumByUidAndCreateTime($uid,$beginMonth,$endMonth);

        $directUsers = $this->userData->getDirectUsersByInviteUid($uid);
        $openIds = [];
        foreach ($directUsers as $item) {
            if(!empty($item['openId'])) {
                array_push($openIds, $item['openId']);
            }
        }
        //团队会员人数统计
        $todayInDirNum = 0;
        $weekInDirNum = 0;
        $monthInDirNum = 0;
        if(!empty($openIds)) {
            $todayInDirNum = $this->userData->getIndirectUsersByInviteOpenId($openIds,$beginToday,$endToday);
            $weekInDirNum = $this->userData->getIndirectUsersByInviteOpenId($openIds,$beginWeek,$endWeek);
            $monthInDirNum = $this->userData->getIndirectUsersByInviteOpenId($openIds,$beginMonth,$endMonth);
        }
        $userCount = new WeChatUserTeamCount();
        $userCount->todayDirNum = intval($todayDirNum);
        $userCount->weekDirNum = intval($weekDirNum);
        $userCount->monthDirNum = intval($monthDirNum);
        $userCount->todayInDirNum = intval($todayInDirNum);
        $userCount->weekInDirNum = intval($weekInDirNum);
        $userCount->monthInDirNum = intval($monthInDirNum);
        return $userCount;
    }

}